<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;

/**
 * 运势相关接口
 * @ApiWeigh (99)
 */
class YunShi extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 查询未来运势
     * @ApiInternal
     * @ApiTitle    (查询未来运势)
     * @ApiSummary  (根据生辰八字查询未来运势)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/yun_shi/weilai)
     * @ApiParams   (name="type", type="integer", required=true, description="历法类型：0=农历，1=公历")
     * @ApiParams   (name="yunshi_year", type="integer", required=true, description="需要测算的公历年份，如：2030")
     * @ApiParams   (name="compute_daily", type="integer", required=false, description="是否算每日运势：1=是，2=否", default=2)
     * @ApiParams   (name="sect", type="integer", required=false, description="流派：1=晚子时日柱算明天，2=晚子时日柱算当天", default=2)
     * @ApiParams   (name="zhen", type="integer", required=false, description="是否考虑真太阳时：1=是，2=否", default=2)
     * @ApiParams   (name="province", type="string", required=false, description="省份，如：北京市")
     * @ApiParams   (name="city", type="string", required=false, description="城市，如：北京")
     * @ApiParams   (name="lang", type="string", required=false, description="语言：zh-cn、en-us、zh-tw", default="zh-cn")
     */
    public function weilai()
    {
        $user = $this->auth->getUser();
        // 检查用户必要信息是否完整
        if (empty($user->realname) || empty($user->birth_date) || empty($user->birth_time) || $user->gender === null) {
            $this->error('请先完善个人信息');
        }
        
        // 解析出生日期和时间
        $birthDate = strtotime($user->birth_date . ' ' . $user->birth_time);
        if ($birthDate === false) {
            $this->error('出生日期时间格式错误');
        }
        
        $params = [
            'name' => $user->realname,
            'sex' => $user->gender,
            'type' => $this->request->post('type', 0, 'intval'),
            'year' => date('Y', $birthDate),
            'month' => date('n', $birthDate),
            'day' => date('j', $birthDate),
            'hours' => date('G', $birthDate),
            'minute' => date('i', $birthDate),
            'yunshi_year' => $this->request->post('yunshi_year', '', 'intval'),
            'compute_daily' => $this->request->post('compute_daily', 2, 'intval'),
            'sect' => $this->request->post('sect', 2, 'intval'),
            'zhen' => $this->request->post('zhen', 2, 'intval'),
            'province' => $this->request->post('province', '', 'trim'),
            'city' => $this->request->post('city', '', 'trim'),
            'lang' => $this->request->post('lang', 'zh-cn', 'trim')
        ];

        // 必填参数验证
        $required = ['type', 'yunshi_year'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if (!in_array($params['type'], [0, 1])) {
            $this->error(__('Invalid type value'));
        }
        if (!in_array($params['compute_daily'], [1, 2])) {
            $this->error(__('Invalid compute_daily value'));
        }
        if (!in_array($params['sect'], [1, 2])) {
            $this->error(__('Invalid sect value'));
        }
        if (!in_array($params['zhen'], [1, 2])) {
            $this->error(__('Invalid zhen value'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Bazi/weilai', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '获取未来运势失败');
            }
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }
    
    /**
     * 查询生肖运势
     *
     * @ApiTitle    (查询生肖每日运势)
     * @ApiSummary  (根据用户生日查询生肖运势)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/yun_shi/shengxiao)
     * @ApiParams   (name="birth_date", type="string", required=false, description="出生日期，格式：YYYY-MM-DD，未登录时必传")
     */
    public function shengxiao()
    {
        $birthDate = $this->request->post('birth_date');
        $isVip = false;
        $today = date('Y-m-d');
        
        if (empty($birthDate)) {
            // 未传入日期时判断登录状态
            if (!$this->auth->isLogin()) {
                $this->error('请输入出生日期');
            }
            
            $user = $this->auth->getUser();
            if (empty($user->birth_date)) {
                $this->error('请先完善出生日期信息');
            }
            $birthDate = $user->birth_date;
            $isVip = $user->vip_expire_time && $user->vip_expire_time > time();
        } else {
            // 验证传入日期格式
            if (!strtotime($birthDate)) {
                $this->error('出生日期格式错误');
            }
            // 已登录时同步会员状态
            if ($this->auth->isLogin()) {
                $user = $this->auth->getUser();
                $isVip = $user->vip_expire_time && $user->vip_expire_time > time();
            }
        }
        
        // 先查询今日缓存
        $cache = \app\common\model\YunshiLog::where([
            'birth_date' => $birthDate,
            'query_date' => $today
        ])->find();
        
        if($cache) {
            $data = json_decode($cache['data'], true);
            // 非会员只返回今日运势
            if (!$isVip) {
                if (isset($data['今日运势'])) {
                    $data = [
                        '运势类型' => $data['运势类型'],
                        '今日运势' => $data['今日运势']
                    ];
                }
            }
            $this->success('获取成功', $data);
        }
        
        // 计算生肖
        $birthYear = date('Y', strtotime($birthDate));
        $shengxiao = ($birthYear - 4) % 12;
        
        $params = [
            'api_key' => config('yuanfenju.api_key'),
            'type' => 1,
            'title_yunshi' => $shengxiao,
            'lang' => 'zh-cn'
        ];

        try {
            $result = YuanfenjuService::instance()->request('/Zhanbu/yunshi', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '获取生肖运势失败');
            }
            
            // 记录查询日志
            \app\common\model\YunshiLog::create([
                'birth_date' => $birthDate,
                'query_date' => $today,
                'data' => json_encode($result['data']),
                'createtime' => time()
            ]);
            
            // 处理返回数据
            $data = $result['data'];
            
            // 非会员只返回今日运势
            if (!$isVip) {
                if (isset($data['今日运势'])) {
                    $data = [
                        '运势类型' => $data['运势类型'],
                        '今日运势' => $data['今日运势']
                    ];
                }
            }
            
            $this->success('获取成功', $data);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }
}